<template>
    <van-list
			v-if="!is_empty"
			v-model="loading"
			:finished="is_finished"
			:offset="300"
			:immediate-check="false"
			finished-text="没有更多了"
			@load="doLoad"
    >
			<msg-item :list="list" />
    </van-list>
    <no-data v-else />
</template>
<script>
import {
	List
} from 'vant'
import {
    getMessage
} from '@api/modules/message'
import NoData from '@cmpt/no-data'
import MsgItem from "../components/msg-item"
import { formatTime } from '@utils/utils'
export default {
	name: 'msg-list',
	props: ['type'],
	components: {
		[List.name]: List,
		[MsgItem.name]: MsgItem,
		[NoData.name]: NoData
	},
	data () {
		return {
			list: [],
			total: 0,
			page: 1,
			limit: 10,
			loading: false,
			is_finished: false,
			is_empty: false
		}
	},
	watch: {
		type (nw) {
			this.reLoad()
		},
	},
	created() {
		this.doLoad()
	},
	mounted(){
		//监测回退
		history.pushState(null, null, document.URL)
		window.addEventListener('popstate', this.forbidback);
	},
	beforeDestroy(){
		//销毁
		window.removeEventListener('popstate',this.forbidback);
	},
	methods: {
		reLoad () {
			this.list = []
			this.total = 0
			this.page = 1
			this.loading = false
			this.is_finished = false
			this.is_empty = false
			this.doLoad()
		},
		async doLoad() {
				this.loading = true
				let param = {
					page: this.page
				}
				if(this.type >= 0){
					param.kind = this.type
				}
				getMessage(param).then(res => {
					let list = res.data
					const now = new Date(),
								seven_ago = new Date(now)
						seven_ago.setDate(now.getDate() - 7)
					// 超过7天判断为已读，不管读没读
					list.messages.forEach(item => {
						if(item.pushed_at.padEnd(13, '0') < seven_ago.getTime()){
							item.received_at = item.readed_at = new Date().getTime()
						}
					})

					this.list = this.list.concat(list.messages)
					this.page++
					
					this.total = list.total
					this.is_finished = this.list.length >= this.total
					this.loading = false
					this.is_empty = this.total <= 0 
				}).catch(err => {
					this.is_finished = this.list.length >= this.total
					this.loading = false
					this.is_empty = this.total <= 0 
				})
		}
	}
}
</script>